<?php
class AdminGroupController extends Controller {
	
	/**
	 * Display a listing of the resource.
	 *
	 * @return Response
	 */
	public function index()
	{
		$groups = Group::orderBy('id', 'desc')->paginate(5);
		 
		return View::make('admins.groups.index', compact('groups'));
	}
	
	
	/**
	 * Show the form for creating a new resource.
	 *
	 * @return Response
	 */
	public function create()
	{
		return View::make('admins.groups.create');
	}
	
	
	/**
	 * Store a newly created resource in storage.
	 *
	 * @return Response
	 */
	public function store()
	{
		$input = Input::all();
		$validation = Validator::make($input, Group::rules());
	
		if ($validation->passes()) {
			Group::create($input);
	
			return Redirect::route('admin.group.index')
				->with('message', 'Created successful.');
		}
	
		return Redirect::back()
			->withInput()
			->withErrors($validation);
	}

	
	/**
	 * Display the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function show($id)
	{
		echo 'show';
	}
	
	
	/**
	 * Show the form for editing the specified resource.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function edit($id)
	{
		$group = Group::find($id);
	
		if (is_null($group)) {
			return Redirect::route('admin.group.index');
		}
		
		return View::make('admins.groups.edit', [
			'group'     => $group,
			'users'     => User::all(),
			'resources' => Resource::all()
		]);
	}
	
	
	/**
	 * Update the specified resource in storage.
	 *
	 * @param  int  $id
	 * @return Response
	 */
	public function update($id)
	{	
		$input = [
			'name' => Input::get('name')
		];
		$validation = Validator::make($input, Group::rules($id));

		if ($validation->passes()) {
			
			$group = Group::find($id);
			$group->update($input);
			
			// Using Sync To Attach Many To Many Models
			$group->users()->sync(Input::get('user_id', []));
			$group->resources()->sync(Input::get('resource_id', []));
				
			return Redirect::route('admin.group.index')
				->with('message', 'Updated successful.');
		}
	
		return Redirect::route('admin.group.edit', $id)
			->withInput()
			->withErrors($validation);
	}
    
    
    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
    	Group::find($id)->delete();
    
    	return Redirect::route('admin.group.index')
    		->with('message', 'Deleted successful.');
    }
}